package com.configtools.controller;

import com.configtools.model.ConfigSettings;
import com.configtools.service.ConfigService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;


import java.net.URL;
import java.util.ResourceBundle;

/**
 * 配置对话框控制器
 * 处理系统配置的用户界面交互
 * 
 * @author ConfigTools
 */
@Slf4j
public class ConfigDialogController implements Initializable {

    private ConfigService configService;
    
    // FXML 注入的控件
    @FXML private TextField packageNameField;
    @FXML private TextField classPrefixField;
    @FXML private TextField classSuffixField;
    @FXML private TextField authorNameField;
    @FXML private CheckBox autoLoadCheckBox;
    @FXML private ComboBox<String> encodingComboBox;
    @FXML private Button confirmButton;
    @FXML private Button cancelButton;
    @FXML private Button resetButton;
    
    // 验证状态显示控件
    @FXML private Label packageValidIcon;
    @FXML private Label prefixValidIcon;
    @FXML private Label suffixValidIcon;
    @FXML private Label packageErrorLabel;
    @FXML private Label prefixErrorLabel;
    @FXML private Label suffixErrorLabel;
    
    // 预览显示控件
    @FXML private Label packagePreviewLabel;
    @FXML private Label classPreviewLabel;
    @FXML private Label pathPreviewLabel;
    @FXML private Label authorPreviewLabel;
    
    /** 原始配置设置 */
    private ConfigSettings originalSettings;
    
    /** 当前配置设置 */
    private ConfigSettings currentSettings;
    
    /** 对话框是否被确认 */
    private boolean confirmed = false;
    
    /** 对话框结果回调 */
    private Runnable onConfigUpdated;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        log.info("初始化配置对话框控制器");
        setupComboBoxes();
        setupEventHandlers();
        setupValidation();
    }
    
    /**
     * 设置下拉框选项
     */
    private void setupComboBoxes() {
        // 设置编码格式选项
        encodingComboBox.getItems().addAll("UTF-8", "GBK", "GB2312", "ISO-8859-1");
        encodingComboBox.setValue("UTF-8"); // 默认选择UTF-8
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 文本字段变化事件
        packageNameField.textProperty().addListener((obs, oldVal, newVal) -> {
            validateAndUpdatePreview();
        });
        
        classPrefixField.textProperty().addListener((obs, oldVal, newVal) -> {
            validateAndUpdatePreview();
        });
        
        classSuffixField.textProperty().addListener((obs, oldVal, newVal) -> {
            validateAndUpdatePreview();
        });
        
        authorNameField.textProperty().addListener((obs, oldVal, newVal) -> {
            updatePreview();
        });
        
        encodingComboBox.valueProperty().addListener((obs, oldVal, newVal) -> {
            updatePreview();
        });
        
        // 回车键确认
        packageNameField.setOnKeyPressed(event -> {
            if (event.getCode() == javafx.scene.input.KeyCode.ENTER) {
                onConfirm();
            }
        });
    }
    
    /**
     * 设置验证规则
     */
    private void setupValidation() {
        // 初始化编码下拉框
        encodingComboBox.getSelectionModel().select("UTF-8");
    }
    
    /**
     * 设置配置服务
     * 
     * @param configService 配置服务实例
     */
    public void setConfigService(ConfigService configService) {
        this.configService = configService;
    }
    
    /**
     * 显示配置对话框
     * 
     * @param stage 父窗口
     * @param onConfigUpdated 配置更新回调
     */
    public void showDialog(Stage stage, Runnable onConfigUpdated) {
        this.onConfigUpdated = onConfigUpdated;
        
        // 加载当前配置
        originalSettings = configService.getCurrentSettings();
        currentSettings = originalSettings.copy();
        
        // 填充界面
        loadSettingsToUI(currentSettings);
        
        // 初始验证和预览
        validateAndUpdatePreview();
        
        // 显示对话框
        stage.show();
        log.info("配置对话框已显示");
    }
    
    /**
     * 将配置设置加载到界面
     * 
     * @param settings 配置设置
     */
    private void loadSettingsToUI(ConfigSettings settings) {
        packageNameField.setText(settings.getPackageName());
        classPrefixField.setText(settings.getClassPrefix());
        classSuffixField.setText(settings.getClassSuffix());
        authorNameField.setText(settings.getAuthorName());
        autoLoadCheckBox.setSelected(settings.isAutoLoadLastDirectory());
        encodingComboBox.getSelectionModel().select(settings.getEncoding());
    }
    
    /**
     * 从界面获取配置设置
     * 
     * @return 配置设置
     */
    private ConfigSettings getSettingsFromUI() {
        ConfigSettings settings = new ConfigSettings();
        settings.setPackageName(packageNameField.getText().trim());
        settings.setClassPrefix(classPrefixField.getText().trim());
        settings.setClassSuffix(classSuffixField.getText().trim());
        settings.setAuthorName(authorNameField.getText().trim());
        settings.setAutoLoadLastDirectory(autoLoadCheckBox.isSelected());
        settings.setEncoding(encodingComboBox.getSelectionModel().getSelectedItem());
        
        // 保留原有的目录历史
        settings.setLastExcelDirectory(originalSettings.getLastExcelDirectory());
        settings.setLastOutputDirectory(originalSettings.getLastOutputDirectory());
        
        return settings;
    }
    
    /**
     * 验证并更新预览
     */
    private void validateAndUpdatePreview() {
        currentSettings = getSettingsFromUI();
        validateSettings();
        updatePreview();
        updateConfirmButtonState();
    }
    
    /**
     * 验证配置设置
     */
    private void validateSettings() {
        // 验证包名
        validatePackageName();
        
        // 验证类名前缀
        validateClassPrefix();
        
        // 验证类名后缀
        validateClassSuffix();
    }
    
    /**
     * 验证包名
     */
    private void validatePackageName() {
        boolean isValid = currentSettings.isValidPackageName();
        packageValidIcon.setVisible(isValid);
        packageErrorLabel.setVisible(!isValid);
        
        if (!isValid) {
            packageErrorLabel.setText("包名格式不正确，请使用小写字母、数字和点号");
        }
    }
    

    
    /**
     * 验证类名前缀
     */
    private void validateClassPrefix() {
        boolean isValid = currentSettings.isValidClassPrefix();
        prefixValidIcon.setVisible(isValid && !currentSettings.getClassPrefix().isEmpty());
        prefixErrorLabel.setVisible(!isValid);
        
        if (!isValid) {
            prefixErrorLabel.setText("类名前缀格式不正确，请使用字母开头的标识符");
        }
    }
    
    /**
     * 验证类名后缀
     */
    private void validateClassSuffix() {
        boolean isValid = currentSettings.isValidClassSuffix();
        suffixValidIcon.setVisible(isValid && !currentSettings.getClassSuffix().isEmpty());
        suffixErrorLabel.setVisible(!isValid);
        
        if (!isValid) {
            suffixErrorLabel.setText("类名后缀格式不正确，请使用字母开头的标识符");
        }
    }
    
    /**
     * 更新预览信息
     */
    private void updatePreview() {
        if (currentSettings == null) return;
        
        // 包名预览
        packagePreviewLabel.setText("包名：" + currentSettings.getPackageName());
        
        // 类名预览
        String exampleClassName = currentSettings.getFullClassName("Player");
        classPreviewLabel.setText("示例类名：" + exampleClassName + ".java");
        
        // 路径预览
        if (!currentSettings.getPackageName().isEmpty()) {
            String fullPath = "src/main/java/" + currentSettings.getPackagePath() + "/";
            pathPreviewLabel.setText("输出路径：" + fullPath);
        } else {
            pathPreviewLabel.setText("输出路径：未设置");
        }
        
        // 作者预览
        authorPreviewLabel.setText("作者：" + currentSettings.getAuthorName());
    }
    
    /**
     * 更新确认按钮状态
     */
    private void updateConfirmButtonState() {
        String validationError = configService.validateSettings(currentSettings);
        confirmButton.setDisable(validationError != null);
    }
    
   
    /**
     * 确认按钮事件
     */
    @FXML
    private void onConfirm() {
        currentSettings = getSettingsFromUI();
        
        // 最终验证
        String validationError = configService.validateSettings(currentSettings);
        if (validationError != null) {
            showErrorAlert("配置验证失败", validationError);
            return;
        }
        
        // 保存配置
        boolean saved = configService.saveSettings(currentSettings);
        if (!saved) {
            showErrorAlert("保存失败", "无法保存配置设置，请检查文件权限");
            return;
        }
        
        confirmed = true;
        closeDialog();
        
        // 通知配置已更新
        if (onConfigUpdated != null) {
            Platform.runLater(onConfigUpdated);
        }
        
        log.info("配置已确认并保存");
    }
    
    /**
     * 取消按钮事件
     */
    @FXML
    private void onCancel() {
        confirmed = false;
        closeDialog();
        log.info("配置对话框已取消");
    }
    
    /**
     * 重置按钮事件
     */
    @FXML
    private void onReset() {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认重置");
        alert.setHeaderText("重置配置");
        alert.setContentText("确定要将所有配置重置为默认值吗？");
        
        alert.showAndWait().ifPresent(result -> {
            if (result == ButtonType.OK) {
                ConfigSettings defaultSettings = ConfigSettings.createDefault();
                loadSettingsToUI(defaultSettings);
                validateAndUpdatePreview();
                log.info("配置已重置为默认值");
            }
        });
    }
    
    /**
     * 关闭对话框
     */
    private void closeDialog() {
        Stage stage = (Stage) confirmButton.getScene().getWindow();
        stage.close();
    }
    
    /**
     * 显示错误提示对话框
     * 
     * @param title 标题
     * @param message 消息
     */
    private void showErrorAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
    
    /**
     * 检查对话框是否被确认
     * 
     * @return 是否确认
     */
    public boolean isConfirmed() {
        return confirmed;
    }
    
    /**
     * 获取当前配置设置
     * 
     * @return 当前配置设置
     */
    public ConfigSettings getCurrentSettings() {
        return currentSettings;
    }
}
